package com.example.backendmanage.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailUtil;
import com.example.backendmanage.common.AjaxResult;
import com.example.backendmanage.common.ReturnCode;
import com.example.backendmanage.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/email")
public class EmailController {
    @Autowired
    RedisService redisService;

    @RequestMapping("/sendEmail")
    public AjaxResult sendEmail(@RequestParam String Email){
        System.out.println("email->"+Email);
        String uuid= IdUtil.fastSimpleUUID();
        String Code= RandomUtil.randomString(4);
        System.out.println(Code);
        redisService.saveCode("emailCode",uuid,Code);
        MailUtil.send(Email,"验证码","你的验证码为:   "+Code+" (五分钟内有效)",false);
        return AjaxResult.success(uuid);
    }

    @RequestMapping("/checkEmail")
    public AjaxResult checkEmail(@RequestParam String uuid,@RequestParam String userInputCode){
        if (StrUtil.isBlank(uuid)){
            return AjaxResult.fail(Integer.valueOf(ReturnCode.CODE_400),"参数错误");
        }
        String Code= redisService.getCodeById("emailCode",uuid);
        if (userInputCode.equals(Code)){
            return AjaxResult.success(true);
        }
        return AjaxResult.success(false);
    }
}
